package servletlearn.cookie;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

@WebServlet(name = "CookieServlet", urlPatterns = "/cServlet")
public class CookieServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();
        out.print("上次访问时间:");

        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals("lastTime")) {
                    long value = Long.parseLong(cookie.getValue());
                    Date date = new Date(value);
                    out.print(date.toLocaleString());
                }
            }
        }


        Cookie lastTime = new Cookie("lastTime", System.currentTimeMillis() + "");
        lastTime.setMaxAge(30 * 24 * 3600);//0为命令删除
        lastTime.setPath("/ZY");
        response.addCookie(lastTime);
    }


}
